package com.authine.cloudpivot.ext.applicationservice;

import com.authine.cloudpivot.ext.listener.MyCancelCallback;
import com.authine.cloudpivot.ext.listener.MyDeliverCallback;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName MQConsumer
 * @Description: TODO
 * @Author fj
 * @Date 2021/7/28
 * @Version V1.0
 **/
@Slf4j
public class MQConsumer extends ApplicationService {
    private final static String QUEUE_NAME = "paas.app.info";
//    private final static String QUEUE_NAME = "paas.app.info.anonymous.TtucxUp0RFGhhu17ZQ_Gng";
    private static final Environment environment = ApplicationContextUtils.getBean(Environment.class);

     static {
         try {
             log.info("方法receivedMessage被调用");
             // 创建连接工厂
             ConnectionFactory factory = new ConnectionFactory();
             //设置RabbitMQ地址
             String host = environment.getProperty("spring.rabbitmq.host");
             String username = environment.getProperty("spring.rabbitmq.username");
             String password = environment.getProperty("spring.rabbitmq.password");
             String port = environment.getProperty("spring.rabbitmq.port");
             factory.setHost(host);
             factory.setPort(Integer.parseInt(port));
             factory.setUsername(username);
             factory.setPassword(password);
             //创建一个新的连接
             Connection connection = factory.newConnection();
             //创建一个通道
             Channel channel = connection.createChannel();
             channel.exchangeDeclare(QUEUE_NAME, "topic", true);
             String queueName = channel.queueDeclare().getQueue();

             channel.queueBind(queueName, QUEUE_NAME, "#");

             log.info(" [*] Waiting for messages. To exit press CTRL+C");

             DeliverCallback deliverCallback = new MyDeliverCallback();
             CancelCallback cancelCallback = new MyCancelCallback();
             channel.basicConsume(queueName, true, deliverCallback, cancelCallback);
         } catch (TimeoutException | IOException e) {
             e.printStackTrace();
         }
     }
}
